package com.jackingod.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

public class ExcelUtil {
	private static final Logger logger = LogManager.getLogger("ExcelUtil");
	
	public static void write(String[] titleNames, 
			List<Object[]> data) throws IOException {
		write("data.xls", "", titleNames, data);
	}
	
	public static void write(String fileName, String sheetName, 
			String[] titleNames, List<Object[]> data) throws IOException {
		write(new File(fileName), sheetName, titleNames, data);
	}
	
	public static void write(File file, String sheetName, 
			String[] titleNames, List<Object[]> data) 
					throws IOException {
		if (file == null) {
			return;
		}
		
		File dir = file.getParentFile();
		if (dir != null) {
			dir.mkdirs();
		}
		
		Workbook wb = new HSSFWorkbook();
		Sheet s = wb.createSheet(sheetName);
		for (int i = 0, len = titleNames.length; i < len; i++) {
			s.setColumnWidth(i, 5000);
		}
		CreationHelper createHelper = wb.getCreationHelper();
		
		// create 2 fonts objects
		Font tf = wb.createFont();
		Font cf = wb.createFont();
		// set title font and cell font
		tf.setFontHeightInPoints((short)16);
		tf.setColor(IndexedColors.BLUE.getIndex());
		cf.setFontHeightInPoints((short)12);
		cf.setColor(IndexedColors.BLACK.getIndex());
		cf.setBoldweight(Font.BOLDWEIGHT_NORMAL);
		
		// create title style and cell style
		CellStyle cs = wb.createCellStyle();
		CellStyle ts = wb.createCellStyle();
		DataFormat df = wb.createDataFormat();
		// set the other cell style and formatting
		cs.setDataFormat(df.getFormat("text"));
		cs.setFont(cf);
		ts.setDataFormat(df.getFormat("text"));
		ts.setFont(tf);
		
		Row r = null;
		Cell c = null;
		// set title for all columns
		r = s.createRow(0);
		for (int i = 0, len = titleNames.length; i < len; i++) {
			c = r.createCell(i);
			c.setCellStyle(ts);
			c.setCellValue(createHelper
					.createRichTextString(titleNames[i]));
		}
		
		logger.debug("data size=" + data.size());
		// create rows and cell, then fill data
		for (int i = 1, len = data.size(); i < len; i++) {
			Object[] objects = (Object[])data.get(i-1);
			r = s.createRow(i);
			for (int j = 0, olen = objects.length; j < olen; j++) {
				c = r.createCell(j);
				c.setCellStyle(cs);
				c.setCellValue(createHelper
						.createRichTextString(objects[j].toString()));
			}			
		}
		
		//save
		OutputStream os = new FileOutputStream(file);
		wb.write(os);
		os.close();
	}
	
}
